package com.itheima.fengkuanglianxi.bookmanager.bookdao;

import com.itheima.fengkuanglianxi.bookmanager.domain.Book;

import java.util.ArrayList;

public class Book2Dao implements BaseBookDao {

    private ArrayList<Book> list = new ArrayList<Book>();

    @Override
    public Book[] getAllBooks() {
        Book[] books = new Book[list.size()];
        for (int i = 0; i < list.size(); i++) {
            Book book = list.get(i);
            books[i] = book;
        }
        return books;
    }

    @Override
    public boolean addBook(Book book) {
        list.add(book);
        return true;
    }

    @Override
    public void deleteBook(String bookId) {

        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            Book book = list.get(i);
            if (book != null) {
                if (book.getBookId().equals(bookId)) {
                    index = i;
                    break;
                }

            }
        }
        if (index != -1){
            list.remove(index);
        }

    }

    @Override
    public void updateBook(Book book) {
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            Book bookArray = list.get(i);
            if(bookArray != null){
                if(bookArray.getBookId().equals(book.getBookId())){
                    index = i;
                    break;
                }
            }
        }
        if(index != -1){
            list.set(index, book);
        }
    }
}
